<!-- src/components/charts/CategoryPieChart.vue -->
<template>
  <el-card class="box-card" shadow="hover" style="height: 600px">
    <template #header>
      <div class="card-header" >📊 文章分类分布图</div>
    </template>
    <div ref="pieChartRef" style="height: 400px; width: 100%"></div>
  </el-card>
</template>

<script setup >
import { onMounted, ref } from 'vue'
import * as echarts from 'echarts'
import { getCategoryArticleCounts } from '@/api/statistics.js'
import '@/assets/css/adstatisStyle.css'
const pieChartRef = ref(null)

const loadChart = async () => {
  try {
    const res = await getCategoryArticleCounts()
    console.log('原始数据:', res.data)

    const filteredData = res.data.filter(item => item.articleCount > 0)
    console.log('过滤后数据:', filteredData)

    if (filteredData.length === 0) {
      console.warn('没有文章数大于0的分类，饼图不渲染')
      return
    }

    const data = filteredData.map(item => ({
      name: item.categoryName,
      value: item.articleCount
    }))

    const chart = echarts.init(pieChartRef.value)
    chart.setOption({
      tooltip: { trigger: 'item' },
      legend: { top: '86%', itemHeight: 15, itemGap: 10 },
      series: [{
        name: '文章分类',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['50%', '42%'],
        avoidLabelOverlap: false,
        itemStyle: { borderRadius: 10, borderColor: '#fff', borderWidth: 2 },
        label: { show: true, formatter: '{b}: {c}篇 ({d}%)' },
        emphasis: { label: { show: true, fontSize: 18, fontWeight: 'bold' } },
        data
      }]
    })

    window.addEventListener('resize', () => chart.resize())
  } catch (err) {
    console.error('加载文章分类图失败:', err)
  }
}


onMounted(() => {
  loadChart()
})
</script>

<style scoped>
.card-header {
  font-weight: bold;
  font-size: 18px;
  color: #409EFF;
}
.box-card{
  height: 600px;
}
</style>
